﻿using System;
using System.Windows.Forms;

namespace ConnectionQualityIcon
{
    public class AppContext : ApplicationContext
    {
        private NotifyIcon notifyIcon;
        private ConnectionMonitor monitor;

        public AppContext()
        {
            notifyIcon = new NotifyIcon() {
                Icon = Properties.Resources.Good,
                ContextMenu = new ContextMenu(new MenuItem[] {
                    new MenuItem("Exit", Exit)
                }),
                Visible = true,
                Text = "Connection Quality",
            };

            monitor = new ConnectionMonitor();
            monitor.Update += new System.Net.NetworkInformation.PingCompletedEventHandler(monitor_Update);
        }

        private void monitor_Update(object sender, System.Net.NetworkInformation.PingCompletedEventArgs e)
        {
            notifyIcon.Text = String.Format("{0} \u00B1 {1} ms", monitor.Latency, monitor.Jitter);
            if (monitor.Jitter < 100 && monitor.Latency < 100)
            {
                notifyIcon.Icon = Properties.Resources.Good;
            }
            else
            {
                notifyIcon.Icon = Properties.Resources.Bad;
            }
        }

        private void Exit(object sender, EventArgs e)
        {
            notifyIcon.Visible = false;

            Application.Exit();
        }
    }
}
